<template>
	<view class="">
		<el-upload class="avatar-uploader" name="avatarfile" :on-success="handleAvatarSuccess"
			:before-upload="beforeAvatarUpload" :headers="headers" :show-file-list="false" :action="action">
			<img v-if="imageUrl" :src="imageUrl" class="avatar">
			<i v-else class="el-icon-plus avatar-uploader-icon"></i>
			<view slot="tip" class="el-upload__tip">{{datas.tip}}</view>
		</el-upload>
	</view>
</template>

<script>
	import {
		URL_IP_HOST,
		URL_PREFIX
	} from '@/util/constant.js'
	export default {
		props: ["data"],
		data() {
			var userInfoData_ = uni.getStorageSync("userInfoData_")
			return {
				imageUrl: '',
				datas: {},
				headers: {
					"Authorization": `Bearer ${userInfoData_ ? userInfoData_.access_token : ""}`,
					"clientid": userInfoData_ ? userInfoData_.client_id : "eeb9377d4b6debbc0a6e8756bbbbb4c7"
				},
				action: URL_IP_HOST + "/user/avatar"
			};
		},
		watch: {
			data: {
				handler: function(newValue) {
					this.imageUrl = newValue.url
				},
				deep: true,
				immediate: true
			}
		},
		created() {
			this.datas = this.data
			this.imageUrl = this.datas.url
			// this.action=URL_IP_HOST+"/resource/oss/upload"
			console.log("地址", this.action);
		},
		methods: {
			handleAvatarSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
				console.log("图片上传成功：", res);
				this.$message({
					message: '图片上传成功!',
					type: 'success',
					center: true,
					offset: 0.1
				});
				// this.$emit('uploadImageClick', res.data)
			},
			beforeAvatarUpload(rawFile) {
				console.log("图片上传格式：", rawFile);
				if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
					this.$message({
						message: '图片格式有误! 仅支持jpg、jpeg、png格式!',
						type: 'error',
						center: true,
						offset: 0.1
					});
					return false
				} else if (rawFile.size / 1024 / 1024 > 2) {
					this.$message({
						message: '图片大小不超过2MB!',
						type: 'error',
						center: true,
						offset: 0.1
					});
					return false
				}
				// return isJPG && isLt2M;
			}
		}
	}
</script>
<style lang="scss">
	::v-deep .avatar-uploader {
		.el-upload {
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
		}
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 90px;
		height: 90px;
		line-height: 90px;
		text-align: center;
	}

	.avatar {
		width: 90px;
		height: 90px;
		display: block;
	}
</style>
